define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    function getQueryString(key)
    {
        let after = window.location.href;
        if(after.indexOf('?') === -1) return null; //如果url中没有传参直接返回空

        after = window.location.search;
        //key存在先通过search取值如果取不到就通过hash来取
        after = after.substr(1) || window.location.hash.split("?")[1];

        if(after)
        {
            var reg = new RegExp("(^|&)"+ key +"=([^&]*)(&|$)");
            var r = after.match(reg);
            if(r != null)
            {
                return  decodeURIComponent(r[2]);
            }
            else
            {
                return null;
            }
        }
    }
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'pt/job/index' + location.search,
                    add_url: 'pt/job/add',
                    edit_url: 'pt/job/edit',
                    // del_url: 'pt/job/del',
                    multi_url: 'pt/job/multi',
                    import_url: 'pt/job/import',
                    table: 'pt_job',
                }
            });

            var table = $("#table");
            var labors = JSON.parse($("#labors").val());

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                escape: false,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Name'), operate: 'LIKE'},
                        {field: 'depart.name', title: __('Pt_depart_id')},
                        {field: 'contactor', title: __('Contactor'), operate: 'LIKE'},
                        {field: 'phone', title: __('Phone'), operate: 'LIKE'},
                        {field: 'salary_mode', title: __('Salary_mode'), searchList: {"hour":__('Salary_mode hour'),"day":__('Salary_mode day'),"stage":__('Salary_mode stage')}, formatter: Table.api.formatter.normal},
                        {field: 'attendance_duration', title: __('Attendance_duration'), operate:'BETWEEN'},
                        {field: 'calc_duration', title: __('Calc_duration'), operate:'BETWEEN'},
                        {field: 'self_salary', title: __('Self_salary') + '(元/小时)', operate:'BETWEEN',
                          formatter: function(value, row, index) {
                            if (row.salary_mode == 'hour') {
                              return value;
                            }
                            return '-';
                          }
                        },
                        {field: 'labor1_salary', title: labors[0]['name'] + '(元/小时)', operate:'BETWEEN',
                          formatter: function(value, row, index) {
                            if (row.salary_mode == 'hour') {
                              return value;
                            }
                            return '-';
                          }
                        },
                        {field: 'labor2_salary', title: labors[1]['name'] + '(元/小时)', operate:'BETWEEN',
                          formatter: function(value, row, index) {
                            if (row.salary_mode == 'hour') {
                              return value;
                            }
                            return '-';
                          }
                        },
                        {field: 'self_salary_day', title: __('Self_salary') + '(元/天)', operate:'BETWEEN',
                          formatter: function(value, row, index) {
                            if (row.salary_mode == 'day') {
                              return value;
                            }
                            return '-';
                          }
                        },
                        {field: 'labor1_salary_day', title: labors[0]['name'] + '(元/天)', operate:'BETWEEN',
                          formatter: function(value, row, index) {
                            if (row.salary_mode == 'day') {
                              return value;
                            }
                            return '-';
                          }
                        },
                        {field: 'labor2_salary_day', title: labors[1]['name'] + '(元/天)', operate:'BETWEEN',
                          formatter: function(value, row, index) {
                            if (row.salary_mode == 'day') {
                              return value;
                            }
                            return '-';
                          }
                        },
                        {field: 'self_salary_stage', title: __('Self_salary') + '(元/场)', operate:'BETWEEN',
                          formatter: function(value, row, index) {
                            if (row.salary_mode == 'stage') {
                              return value;
                            }
                            return '-';
                          }
                        },
                        {field: 'labor1_salary_stage', title: labors[0]['name'] + '(元/场)',
                          formatter: function(value, row, index) {
                            if (row.salary_mode == 'stage') {
                              return value;
                            }
                            return '-';
                          }
                        },
                        {field: 'labor2_salary_stage', title: labors[1]['name'] + '(元/场)',
                          formatter: function(value, row, index) {
                            if (row.salary_mode == 'stage') {
                              return value;
                            }
                            return '-';
                          }
                        },
                        {field: 'added1_fee', title: __('Added1_fee'), operate:'BETWEEN'},
                        {field: 'added2_fee', title: __('Added2_fee'), operate:'BETWEEN'},
                        {field: 'is_road', title: __('路费'), operate: 'LIKE', 
                          formatter: function(value, row, index) {
                            if (value == 'n') {
                                return '<font color="red">' + row.is_road_text + '</font>';
                            }
                            return '<font color="blue">' + row.is_road_text + '</font>';
                          }
                        },
                        {field: 'self_sevice_fee', title: __('Self_sevice_fee'), operate:'BETWEEN'},
                        {field: 'status', title: __('Status'), searchList: {"hidden":__('Status hidden'),"normal":__('Status normal')}, formatter: Table.api.formatter.status},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {
                          field: 'operate', 
                          title: __('Operate'), 
                          table: table, 
                          events: Table.api.events.operate, 
                          buttons: [
                              {
                                  name: 'arrange',
                                  text: __('打卡点管理'),
                                  icon: 'fa',
                                  classname: 'btn btn-info btn-xs btn-detail btn-dialog',
                                  url: function (row) {
                                      return Fast.api.fixurl('pt/job/clockIndex?job_id=' + row.id)
                                  },
                                  extend: "data-area='[\"60%\", \"60%\"]'",
                              },
                              {
                                  name: 'arrange',
                                  text: __('人员管理'),
                                  icon: 'fa',
                                  classname: 'btn btn-info btn-xs btn-detail btn-dialog',
                                  url: function (row) {
                                      return Fast.api.fixurl('pt/job/arrange?id=' + row.id)
                                  },
                                  extend: "data-area='[\"95%\", \"95%\"]'",
                              },
                              {
                                  name: 'arrange',
                                  text: __('复制新增'),
                                  icon: 'fa',
                                  classname: 'btn btn-info btn-xs btn-detail btn-dialog',
                                  url: function (row) {
                                      return Fast.api.fixurl('pt/job/copy/ids/' + row.id)
                                  },
                                  extend: "data-area='[\"50%\", \"50%\"]'",
                              },
                          ],

                          formatter: Table.api.formatter.operate

                        }
                    ]
                ],
                showToggle: false,
                showColumns: false,
                showExport: false,
                commonSearch: false,
                search: false,
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        arrange: function () {
            const option = {
                // 支持引入组件
                setup(){
                    const {ref, reactive, onMounted, nextTick, watch, toRefs} = Vue;
                    const workCycleList = ref([
                          {
                            date: "2024-09-01",
                            type: "important",
                            workShift: "白班",
                            workTime: "08:00 - 20:00",
                          },
                          {
                            date: "2024-09-02",
                            type: "common",
                            workShift: "白班",
                            workTime: "08:00 - 18:00",
                          },
                          {
                            date: "2024-09-04",
                            type: "common",
                            workShift: "白班",
                            workTime: "08:00 - 18:00",
                          },
                          {
                            date: "2024-10-05",
                            type: "common",
                            workShift: "白班",
                            workTime: "08:00 - 18:00",
                          },
                        ])
                    const pillData = ref([])
                    const showPill = ref(false) 
                    const dialogTitle = ref('');

                    const value = ref(new Date()) //当前选中的日期
                    const queryDate = ref('');

                    const jobData = ref([])
                    const showJob = ref(false)

                    const showDialogDay = ref(false)
                    const showDialogBatch = ref(false)
                    const showDialogAdd = ref(false)

                    const initFormDay = {
                      startDate: '', 
                      endDate: '',
                      planTotal: 1,
                      jobId: 0,
                    }

                    const formDay = ref(initFormDay)


                    const calendar = ref()
                    const selectDate = (val) => {
                      calendar.value.selectDate(val);
                    };

                    onMounted(()=>{
                        loadData()
                        Controller.api.bindevent();  
                    })
                    watch(value, (newVal, oldVal) => {
                      const newd = this.dateFormat('YYYY-mm-dd',newVal)
                      const newdate = this.dateFormat('YYYY-mm',newVal)
                      const olddate = this.dateFormat('YYYY-mm',oldVal)
                      console.log('newVal =>', newdate)
                      console.log('oldVal =>', olddate)
                      if (newdate !== olddate) {
                          queryDate.value = newd
                          loadData()
                      }
                    })
                    
                    function showDay() {
                      showDialogDay.value = true
                    }

                    function onSubmitDay() {
                      const jobId = $('#jobId').val()
                      formDay.value.jobId = jobId
                      const params = Object.assign({}, formDay.value)
                      params.startDate = this.dateFormat('YYYY-mm-dd', params.startDate)
                      params.endDate = this.dateFormat('YYYY-mm-dd', params.endDate)
                      console.log('formDay =>', params)
                      Backend.api.toastr.positionClass = 'toast-bottom-right';
                      $.ajax({
                          url: `pt/job/handlePlanDay`,
                          type: 'post',
                          dataType: 'json',
                          data: params,
                          success: function (ret) {
                              if (ret.hasOwnProperty("code")) {
                                  var data = ret.hasOwnProperty("data") && ret.data != "" ? ret.data : "";
                                  if (ret.code === 1) {
                                      loadData()
                                      onCancelDay()
                                      Backend.api.toastr.success('岗位日计划设置已保存');
                                  } else {
                                      Backend.api.toastr.error(ret.msg);
                                  }
                              }
                          }, error: function (e) {
                              Backend.api.toastr.error(e.message);
                          }
                      });

                    }
                    
                    function onCancelDay() {
                      formDay.value.startDate = ''
                      formDay.value.endDate = ''
                      formDay.value.planTotal = 0
                      showDialogDay.value = false
                    }

                    function showBatch() {
                      const jobId = $('#jobId').val()
                      Fast.config.openArea = ["90%", "90%"]
                      Fast.api.open("pt/person/batch?jobId=" + jobId, "批量岗位设置", {
                          callback:function(value){
                            console.log('batch value =>', value)
                          }
                      });
                      // showDialogBatch.value = true
                    }
                    
                    function loadData() {
                        const jobId = $('#jobId').val()
                        const params = {
                              date: queryDate.value,
                              jobId
                        }
                        console.log('params =>', params)
                        $.ajax({
                            url: `pt/job/loadPlan`,
                            type: 'post',
                            dataType: 'json',
                            data: params,
                            success: function (ret) {
                                if (ret.hasOwnProperty("code")) {
                                    var data = ret.hasOwnProperty("data") && ret.data != "" ? ret.data : "";
                                    if (ret.code === 1) {
                                        jobData.value = ret.data
                                    } else {
                                        Backend.api.toastr.error(ret.msg);
                                    }
                                }
                            }, error: function (e) {
                                Backend.api.toastr.error(e.message);
                            }
                        });
                    }
                    function handleClick(d) {
                        console.log('handleClick =>', d)
                        const jobId = $('#jobId').val()
                        Fast.config.openArea = ["90%", "90%"]
                        Fast.api.open("pt/person/viewJob?jobId=" + jobId + "&date=" + d['day'], d['day'] + "岗位查看", {
                            callback:function(value){
                              console.log('handleClick =>', value)
                            }
                        });
                    }

                    function refreshData() {
                        loadData()
                    }
                    return {
                      workCycleList,
                      pillData,
                      showPill,
                      dialogTitle,

                      value,
                      calendar,
                      selectDate,
                      handleClick,

                      jobData,
                      showJob,
                      showDialogDay,
                      showDialogBatch,
                      showDialogAdd,
                      
                      showDay,
                      onSubmitDay,
                      onCancelDay,
                      formDay,

                      showBatch,
                      refreshData,
                    };
                }
                
            }
            createApp('app', option)
        },
        global_job: function () {
            var queryDate = $("#query_date").val();
            // Table.api.init();
            Table.api.init({
                extend: {
                    index_url: 'pt/job/jobs?query_date=' + queryDate,
                    add_url: '',
                    edit_url: '',
                    del_url: '',
                    multi_url: '',
                    table: '',
                },
            });
            var ex = function (t) {
                // 表格1
                var table = $("#table" + t);
                table.bootstrapTable({
                    // url: 'pt/job/jobs?id=' + t + '&query_date=' + queryDate ,
                    url: $.fn.bootstrapTable.defaults.extend.index_url + '&id=' + t,
                    toolbar: '#toolbar' + t,
                    pk: 'id',
                    sortName: 'id',
                    search: false,
                    pagination: false,
                    columns: [
                        [
                            {field: 'id', title: 'ID', visible: false},
                            {field: 'job_name', title: __('岗位名称'), width: 300},
                            {field: 'plan_total', title: __('计划人次'), width: 200},
                            {field: 'consume_total', title: __('消耗人次'), width: 200},
                            {field: 'persons', title: __('已安排人员'), width: 500,
                              formatter: function(value, row, index) {
                                var str = "";
                                for(var i in value) {
                                    // str += value[i]['name'] + '(' + value[i]['phone'] + '),'
                                    str += value[i]['name'] + ','
                                }
                                return str;
                              }
                            },
                            // {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                            {   
                              field: 'operate', 
                              title: __('Operate'), 
                              table: table, 
                              events: Table.api.events.operate, 
                              buttons: [
                                  {   
                                      name: 'arrange',
                                      text: __('人员管理'),
                                      icon: 'fa',
                                      classname: 'btn btn-info btn-xs btn-detail btn-dialog',
                                      url: function (row) {
                                          // Fast.config.openArea = ["80%", "80%"]
                                          return Fast.api.fixurl("pt/person/viewJob?jobId=" + row.job_id + "&date=" + row.cur_date, row.cur_date + "岗位查看", {
                                              callback:function(value){
                                                console.log('handleClick =>', value)
                                              }
                                          });
                                      },  
                                      extend: "data-area='[\"100%\", \"100%\"]'",
                                  },  
                              ],  

                              formatter: Table.api.formatter.operate

                            } 
                        ]
                    ],
                    showToggle: false,
                    showColumns: false,
                    showExport: false,
                    commonSearch: false,
                    search: false,
                });

                // 为表格2绑定事件
                Table.api.bindevent(table);

                return table;
            }
            var table = {}
            var tables = $("#tables").val(); 
            var tableData = JSON.parse(tables)
            for(var t in tableData) {
                ex(tableData[t], queryDate)
            }

            var refreshQuery = function () {
                queryDate = $("#query_date").val();
                for(var t in tableData) {
                    var tt = ex(tableData[t], queryDate)
                    tt.bootstrapTable('refresh', {
                      url: 'pt/job/jobs?id=' + tableData[t] + '&query_date=' + queryDate
                    })
                }
                Fast.api.ajax({
                    url:'pt/job/global_job?query_date=' + queryDate
                }, function(res){
                    console.log('export =>', res)
                    $("#plan_total").html(res['plan_total']) 
                    $("#consume_total").html(res['consume_total']) 
                }, function(){
                    Backend.api.toastr.error('请求失败');
                });
            }
            
            $(".btn-refresh").on("click", function() {
                refreshQuery();
            })
            $(".btn-embossed").on("click", function() {
                refreshQuery();
            })
            $(".btn-export").on("click", function() {
                queryDate = $("#query_date").val();
                Fast.api.ajax({
                    url:'pt/job/export?query_date=' + queryDate
                }, function(res){
                    console.log('export =>', res)
                    window.location.href=res['file']
                }, function(){
                    console.log('导出失败');
                    Backend.api.toastr.error('导出失败');
                });
            })
            Form.api.bindevent($("form[role=form]"));
        },
        global_fee: function () {
            var queryDate = $("#query_date").val();
            // Table.api.init();
            Table.api.init({
                extend: {
                    index_url: 'pt/job/fees?query_date=' + queryDate,
                    add_url: '',
                    edit_url: '',
                    del_url: '',
                    multi_url: '',
                    table: '',
                },
            });
            var ex = function (t) {
                // 表格1
                var table = $("#table" + t);
                table.bootstrapTable({
                    // url: 'pt/job/jobs?id=' + t + '&query_date=' + queryDate ,
                    url: $.fn.bootstrapTable.defaults.extend.index_url + '&id=' + t,
                    toolbar: '#toolbar' + t,
                    pk: 'id',
                    sortName: 'id',
                    search: false,
                    pagination: false,
                    columns: [
                        [
                            {field: 'id', title: 'ID', visible: false},
                            {field: 'job_name', title: __('岗位名称'), width: 300},
                            {field: 'total_fee', title: __('费用(元)'), width: 200},
                            {field: 'consume_total', title: __('人次'), width: 200},
                            {field: 'intern_total', title: __('实习生'), width: 200},
                            {field: 'parttime_total', title: __('兼职'), width: 200},
                            // {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                        ]
                    ],
                    showToggle: false,
                    showColumns: false,
                    showExport: false,
                    commonSearch: false,
                    search: false,
                });

                // 为表格2绑定事件
                Table.api.bindevent(table);

                return table;
            }
            var table = {}
            var tables = $("#tables").val(); 
            var tableData = JSON.parse(tables)
            for(var t in tableData) {
                ex(tableData[t], queryDate)
            }

            var refreshQuery = function () {
                queryDate = $("#query_date").val();
                for(var t in tableData) {
                    var tt = ex(tableData[t], queryDate)
                    tt.bootstrapTable('refresh', {
                      url: 'pt/job/fees?id=' + tableData[t] + '&query_date=' + queryDate
                    })
                }
            }
            
            $(".btn-refresh").on("click", function() {
                refreshQuery();
            })
            $(".btn-embossed").on("click", function() {
                refreshQuery();
            })
            Form.api.bindevent($("form[role=form]"));
        },
        add: function () {
            $(".daywork").hide();
            $(".stagework").hide();
            $("#c-salary_mode").on("change", function () {
                var salaryMode = $('#c-salary_mode').val();
                console.log('mode =>', salaryMode);
                $(".hourwork").hide();
                $(".daywork").hide();
                $(".stagework").hide();
                if (salaryMode == 'hour') {
                    $(".hourwork").show();
                }
                if (salaryMode == 'day') {
                    $(".daywork").show();
                }
                if (salaryMode == 'stage') {
                    $(".stagework").show();
                }
            }) 
            Controller.api.bindevent();
        },
        edit: function () {
            $(".daywork").hide();
            $(".stagework").hide();
            $(".hourwork").hide();
            var salaryModeInit = $('#c-salary_mode').val();
            if (salaryModeInit == 'hour') {
                $(".hourwork").show();
            }
            if (salaryModeInit == 'day') {
                $(".daywork").show();
            }
            if (salaryModeInit == 'stage') {
                $(".stagework").show();
            }
            $("#c-salary_mode").on("change", function () {
                var salaryMode = $('#c-salary_mode').val();
                console.log('mode =>', salaryMode);
                $(".hourwork").hide();
                $(".daywork").hide();
                $(".stagework").hide();
                if (salaryMode == 'hour') {
                    $(".hourwork").show();
                }
                if (salaryMode == 'day') {
                    $(".daywork").show();
                }
                if (salaryMode == 'stage') {
                    $(".stagework").show();
                }
            }) 
            Controller.api.bindevent();
        },
        copy: function () {
            $(".daywork").hide();
            $(".stagework").hide();
            $(".hourwork").hide();
            var salaryModeInit = $('#c-salary_mode').val();
            if (salaryModeInit == 'hour') {
                $(".hourwork").show();
            }
            if (salaryModeInit == 'day') {
                $(".daywork").show();
            }
            if (salaryModeInit == 'stage') {
                $(".stagework").show();
            }
            $("#c-salary_mode").on("change", function () {
                var salaryMode = $('#c-salary_mode').val();
                console.log('mode =>', salaryMode);
                $(".hourwork").hide();
                $(".daywork").hide();
                $(".stagework").hide();
                if (salaryMode == 'hour') {
                    $(".hourwork").show();
                }
                if (salaryMode == 'day') {
                    $(".daywork").show();
                }
                if (salaryMode == 'stage') {
                    $(".stagework").show();
                }
            }) 
            Controller.api.bindevent();
        },
        clockindex: function () {
            var jobId = getQueryString('job_id');
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'pt/job/clockIndex' + location.search,
                    add_url: 'pt/job/clockAdd?job_id=' + jobId,
                    edit_url: 'pt/job/clockEdit?job_id='+ jobId,
                    del_url: 'pt/job/clockDel?job_id=' + jobId,
                    multi_url: 'pt/job/multi',
                    import_url: 'pt/job/import',
                    table: 'pt_job',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {field: 'address', title: __('地址')},
                        {field: 'lng', title: __('经度')},
                        {field: 'lat', title: __('纬度')},
                        {field: 'radius', title: __('打卡半径(米)')},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ],
                showToggle: false,
                showColumns: false,
                showExport: false,
                commonSearch: false,
                search: false,
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        clockadd: function () {
            Controller.api.bindevent();
        },
        clockedit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
